import React, { useEffect } from 'react';
import { useSelector, useDispatch } from 'react-redux';
import { fetchPosts } from '../../store/postsSlice';

function PostsList() {
  const dispatch = useDispatch();
  // 从 store 中获取 posts 切片的状态
  const { data: posts, status, error } = useSelector(state => state.posts);

  useEffect(() => {
    // 触发异步 action 获取数据
    if (status === 'idle') {
      dispatch(fetchPosts());
    }
  }, [status, dispatch]);

  if (status === 'loading') return <div>加载中...</div>;
  if (status === 'failed') return <div>错误：{error}</div>;

  return (
    <ul>
      {posts.map(post => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}

export default PostsList;